/**
 * @author Ahammer
 * @date   2009
 * @update 2009 11 elimination of automatic "_" (at two positions)
 * @update 2010 09 added progress bar functionality
 * 
 */

/*
 * This file is part of Iqm.
 * Copyright (c) 2010-2011 Helmut Ahammer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package main;

import java.awt.Toolkit;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/** 
 * 
 * */
public class SaveSequence {
	
	//private static File currImgDir;

	public static void run() {
		if (IqmTools.getCurrTankIndex() < 0){
			Board.appendTexln("SaveSequence: There aren't any images to save");
			return;
		}
		JFileChooser fc = null;
		//JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));// im eclipse system

		try {fc = new JFileChooser();
		}
		catch (Throwable e) {
			System.out.println("SaveSequence: This plugin requires Java 2 or Swing.");
			return;
		}
	
		fc.setMultiSelectionEnabled(false);
		fc.setDialogType(JFileChooser.SAVE_DIALOG);
		//fc.setDialogType(JFileChooser.);
		fc.setDialogTitle("Save an image sequence");
		FileNameExtensionFilter filt     = new FileNameExtensionFilter("Image files", "tif", "tiff", "jpg", "jpeg", "png", "bmp");
		FileNameExtensionFilter filtTIFF = new FileNameExtensionFilter("tif", "tif");		 		
		fc.addChoosableFileFilter(filt);
	    fc.addChoosableFileFilter(filtTIFF);
	    fc.addChoosableFileFilter(new FileNameExtensionFilter("jpg", "jpg"));
	    fc.addChoosableFileFilter(new FileNameExtensionFilter("png", "png"));
	    fc.addChoosableFileFilter(new FileNameExtensionFilter("bmp", "bmp"));
	    fc.setFileFilter(filt);        //default setting
	    //fc.setFileFilter(filtTIFF);  //default setting

 
        File currImgDir = IqmTools.getCurrImgPath();
        //System.out.println("Open: " + defaultDir.toString());
		fc.setCurrentDirectory(currImgDir);
	       
		int returnVal = fc.showSaveDialog(fc);
		if (returnVal!=JFileChooser.APPROVE_OPTION) {
			Board.appendTexln("SaveSequence: Error: No image selected");
			return;
		}	
		File file = fc.getSelectedFile();	
		if (file.exists()){
			 Toolkit.getDefaultToolkit().beep();
			 int selected = JOptionPane.showConfirmDialog (null, "File sequence already exists, Overwrite?", "WARNING", JOptionPane.OK_CANCEL_OPTION);
			 if (selected == JOptionPane.CANCEL_OPTION){
				 Board.appendTexln("SaveSequence: Image(s) not saved");
				 return;
			 }
		}
		//System.out.println("SaveSingle: fc.getFileFilter().getDescription()" + fc.getFileFilter().getDescription());
		String enc = "default"; //default
		String ext = "default";
		if (file.toString().toLowerCase().endsWith("tif")){
			enc = "TIFF";
			ext = "tif";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx)); //eliminieren der Endung
		}
		if (file.toString().toLowerCase().endsWith("jpg")){
			enc = "JPEG";
			ext = "jpg";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx));
		}
		if (file.toString().toLowerCase().endsWith("png")){
			enc = "PNG";
			ext = "png";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx));
		}
		if (file.toString().toLowerCase().endsWith("bmp")){
			enc = "BMP";
			ext = "bmp";
			int idx = file.toString().lastIndexOf(".");
			file = new File((String) file.toString().subSequence(0, idx));
		}
		
		//Name ohne extension geschrieben
		if (enc.equals("default")){
			if (fc.getFileFilter().getDescription().equals("tif") || fc.getFileFilter().getDescription().equals("Image files")){
				enc = "TIFF";
				ext = "tif";
			}
			if (fc.getFileFilter().getDescription().equals("jpg")){
				enc = "JPEG";
				ext = "jpg";
			}
			if (fc.getFileFilter().getDescription().equals("png")){
				enc = "PNG";
				ext = "png";
			}
			if (fc.getFileFilter().getDescription().equals("bmp")){
				enc = "BMP";
				ext = "bmp";
			}

		}
		//set default directory for further processing
		currImgDir  = IqmTools.getCurrImgPath();
		currImgDir = fc.getCurrentDirectory();
		IqmTools.setCurrImgPath(currImgDir);
		SaveSequence.saveSequence(file, ext, enc);
	}	
	public static void saveSequence(File file, String ext, String enc){
		boolean virtFlag = false;
	    int index = IqmTools.getCurrTankIndex();
	    if (index == -1) {
		    System.out.println("Tank: no images available");
	    	return;
	    }
		if (Tank.getCurrentTankDataAt(index).firstElement() instanceof PlanarImage) virtFlag = false;
		if (Tank.getCurrentTankDataAt(index).firstElement() instanceof File)        virtFlag = true;  
		int length = Tank.getCurrentTankDataAt(index).getSize();
		PlanarImage pi = null;
	
		String name = file.toString()+String.format("%04d",1)+"."+ext;
		File fileTest = new File(name);
		if (fileTest.exists()){
			 Toolkit.getDefaultToolkit().beep();
			 int selected = JOptionPane.showConfirmDialog (null, "File sequence already exists, Overwrite?", "WARNING", JOptionPane.OK_CANCEL_OPTION);
			 if (selected == JOptionPane.CANCEL_OPTION){
				 Board.appendTexln("SaveSequence: Image(s) not saved");
				 return;
			 }
		}
		for (int n=0; n< length; n++) {	
			int proz = (n+1)*100;
   			proz = proz/length;
   			Manager.setProgressBarStack(proz);
			if (!virtFlag) pi = (PlanarImage) Tank.getCurrentTankDataAt(index).getElementAt(n);
			if (virtFlag)  pi = JAI.create("fileload", Tank.getCurrentTankDataAt(index).getElementAt(n).toString());
			name = file.toString()+String.format("%04d",n+1)+"."+ext;
			if (pi.getSampleModel().getDataType() != DataBuffer.TYPE_BYTE){ //only tiff allowed for non byte data
				if (enc != "TIFF"){
					Board.appendTex("SaveSingle: Note: Only byte data is allowed for "+enc+ " format!");
					return;
				}
			}
			JAI.create("filestore", pi, name, enc);	
		}
		Board.appendTexln("SaveSequence: Current image(s) saved to: " + file + "0001."+ext+",2,3,.....");
		File currImgDir = IqmTools.getCurrImgPath();    
		//Save property to iqm.ini file
		IqmTools.setIqmIniFile("CurrImgPath", currImgDir.toString());
		Manager.setProgressBarStack(0);			
	}

}
